package tut.topic.concurent.CopyOnWriteArrayList;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class ArrayListVsCopyOnWriteArrayListTest {
	public final static void main(String args[]) {


		CopyOnWriteArrayList<String>  list = new CopyOnWriteArrayList<String> ();
		list.add("vivek");
		list.add("kumar");
		Iterator<String>  i = list.iterator();
		while (i.hasNext()) {
			System.out.println(i.next());
			list.add("abhishek");  // We did not get any ConcurrentModificationExceptionat as CopyOnWriteArrayList keeps a copy of original List and iterate over this.
								//The new value which has been added is merged to copy of orignal array only after Iteration is over.
		}
		System.out.println("After modification:");
		Iterator<String>  i2 = list.iterator();
		while (i2.hasNext()) {
			System.out.println(i2.next());
		}

		System.out.println("---------------");
		List<String> list3 = new ArrayList<String>();
		list3.add("vivek");
		list3.add("kumar");
		Iterator<String> i3 = list3.iterator();
		while (i3.hasNext()) {
			System.out.println(i3.next());
			list3.add("abhishek");  // As we have modified the ArrayList after displaying first element, it will throw a ConcurrentModificationException at when we call next() next time.
									//We can not use iterator of CopyOnWriteArrayList to modify the List.
		}
	}
}
